package com.example.xx.config;

import com.example.xx.util.Code;
import com.example.xx.util.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 这个类是权限不足的异常处理
 * @author ：yangan
 * @date ：2021/1/19 3:08 下午
 * @description：
 * @version:
 */
@Component
public class QuanXianBuZuconfig implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        System.out.println("权限不足");
        // 响应json数据给前端
        httpServletResponse.setContentType("application/json;charset=utf-8");
        // 封装响应数据
        Result result = new Result(Code.NO_ACCESS,"权限不足");
        // 将响应数据转换为json格式
        ObjectMapper mapper = new ObjectMapper();
        // 将响应数据转换为json格式
        String s = mapper.writeValueAsString(result);
        // 响应给前端 并且结束请求
        httpServletResponse.getWriter().write(s);
        System.out.println(s);
        // 打印异常信息
        e.printStackTrace();
    }
}
